<?php
namespace app\controller;

use app\BaseController;
use think\facade\Request;
use think\facade\Validate;
use think\facade\Db;
class Feedback extends BaseController {
    public function index() {
        // 获取token并验证用户
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        
        $token = $matches[1];
        $user = Db::name('think_users')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }

        // 验证参数
        $validate = Validate::rule([
            'suggestion' => 'require|max:100',
            'photos' => 'array'
        ]);
        
        $params = Request::post();
        if (!$validate->check($params)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        try {
            Db::startTrans();
            
            // 保存反馈
            $data = [
                'user_id' => $user['id'],
                'suggestion' => $params['suggestion'],
                'photos' => isset($params['photos']) ? json_encode($params['photos']) : null,
                'status' => 0,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            Db::name('think_feedbacks')->insert($data);
            Db::commit();
            
            return json(['code' => 200, 'msg' => '反馈提交成功']);
            
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => '服务器错误：' . $e->getMessage()]);
        }
    }
}